package com.liangfeng.readnews.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.liangfeng.readnews.NewsService;
import com.liangfeng.readnews.R;
import com.liangfeng.readnews.adapter.MyAdapter;
import com.liangfeng.readnews.bean.NewsBean;
import com.liangfeng.readnews.ui.activity.NewsDetailActivity;
import com.liangfeng.readnews.util.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by mzf on 2017/4/21.
 */

public class NewsListFragment extends Fragment {

    NewsService newsService;
    private String appkey;
    private String channel;
    private String start;
    private final String APP_KEY = "6d176c4abf2aaecd";
    private final String REFRESH = "REFRESH";
    private final String LOAD_MORE = "LOAD_MORE";
    private ListView lv_news_list;
    /**
     * 保存最新获取的新闻条目
     */
    private List<NewsBean.Result.NewData> nowList;
    /**
     * 保存所有的新闻条目
     */
    private List<NewsBean.Result.NewData> baseList;
    /**
     * 临时存放nowList+baseList
     */

    private int count = 0;
    private List<NewsBean.Result.NewData> tempList;
    private View view;
    private PullToRefreshLayout pullToRefreshLayout;
    private MyAdapter adapter;
    private String title;
    private Handler handler;

    public NewsListFragment(NewsService newsService, String title) {
        this.newsService = newsService;
        this.title = title;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {


        handler = getHandle();

        baseList = new ArrayList<>();
        tempList = new ArrayList<>();

        initViewAndListener(inflater, handler);

        channel = title;
        start = "0";
        getNews(handler, REFRESH);
        return view;
    }

    private void initViewAndListener(LayoutInflater inflater, final Handler handler) {
        view = inflater.inflate(R.layout.fragment_news_list, null);
        lv_news_list = (ListView) view.findViewById(R.id.lv_news_list);

        pullToRefreshLayout = (PullToRefreshLayout) view.findViewById(R.id.ptrl);
        pullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                start = "0";
                getNews(handler, REFRESH);
            }

            @Override
            public void loadMore() {
                count++;
                start = String.valueOf(count * 10);
                getNews(handler, LOAD_MORE);
            }
        });

        //设置条目监听
        lv_news_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtils.showLong(getActivity(), "item" + position);
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                intent.putExtra("url", baseList.get(position).getUrl());
                startActivity(intent);
            }

        });
    }

    @NonNull
    private Handler getHandle() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String flag = (String) msg.obj;
                //
                for (NewsBean.Result.NewData newData : nowList) {
                    baseList.add(newData);
                }

                if (adapter == null) {
                    adapter = new MyAdapter(baseList, getActivity());
                    lv_news_list.setAdapter(adapter);
                } else {
                    switch (flag) {
                        case REFRESH:
                            //清空临时集合
                            tempList.clear();
                            //先将最新的新闻条目放入临时集合
                            for (NewsBean.Result.NewData newData : nowList) {
                                tempList.add(newData);
                            }
                            tempList.addAll(baseList);
                            baseList = tempList;
                            //通知数据刷新
                            adapter.notifyDataSetChanged();
                            pullToRefreshLayout.finishRefresh();
                            break;
                        case LOAD_MORE:
                            LogUtils.e(">>>>>>>LOAD_MORE1<<<<<<<<");
                            int temp = baseList.size();
                            for (NewsBean.Result.NewData newData : nowList) {
                                baseList.add(newData);
                            }
                            //通知数据刷新
                            LogUtils.e(">>>>>>>LOAD_MORE2<<<<<<<<");
                            adapter.notifyDataSetChanged();
                            pullToRefreshLayout.finishLoadMore();
                            lv_news_list.setSelection(temp);
                            LogUtils.e(">>>>>>>LOAD_MORE3<<<<<<<<");
                            break;

                    }

                }

            }

        };
    }

    private void getNews(final Handler handler, final String flag) {


        newsService.getNews(getMap(APP_KEY, channel, start))
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<NewsBean>() {


                    @Override
                    public void onCompleted() {
                        LogUtils.e("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("onError");
                        LogUtils.e("e   :   " + e.toString());

                    }

                    @Override
                    public void onNext(NewsBean newsBean) {
                        LogUtils.e("onNext");
                        LogUtils.e("newsBean    :   " + newsBean.toString());
                        nowList = newsBean.getResult().getList();
                        LogUtils.e("list    :   " + nowList);
                        Message message = new Message();
                        message.obj = flag;
                        handler.sendMessage(message);
                    }
                });
    }


    private HashMap getMap(String appkey, String channel, String start) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appkey", appkey);
        map.put("channel", channel);
        map.put("start", start);
        return map;
    }

}
